package com.fortune.rainshine.controller;

import com.fortune.rainshine.feign.common.RedisFeign;
import com.fortune.rainshine.feign.common.SmsSendFeign;
import com.fortune.rainshine.feign.service.ShopFeign;
import com.fortune.rainshine.feign.system.CustomerCardFeign;
import com.fortune.rainshine.feign.system.CustomerFeign;
import com.fortune.rainshine.feign.system.UserFeign;
import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.enums.ErrorCodes;
import com.fortune.rainshinecommon.enums.RedisConstantEnum;
import com.fortune.rainshinecommon.enums.ResultCode;
import com.fortune.rainshinecommon.model.CustomerModel;
import com.fortune.rainshinecommon.model.ShopModel;
import com.fortune.rainshinecommon.model.SmsParamsModel;
import com.fortune.rainshinecommon.model.system.CustomerCardModel;
import com.fortune.rainshinecommon.model.system.CustomerServiceTotalModel;
import com.fortune.rainshinecommon.model.system.User;
import com.fortune.rainshinecommon.util.RandomNumUtil;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

/**
 * @program: rainShine
 * @description:
 * @author: tangyn
 * @create: 2019-05-22
 **/
@RestController
@RequestMapping("customerCardController")
public class CustomerCardController {
    private static final Logger logger = LoggerFactory.getLogger(CustomerCardController.class);

    @Autowired
    private CustomerFeign customerFeign;
    @Autowired
    private RedisFeign redisFeign;
    @Autowired
    private CustomerCardFeign customerCardFeign;
    @Autowired
    private SmsSendFeign smsSendFeign;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private ShopFeign shopFeign;
    @Value("${smsSend.number}")
    private Integer number;

    @RequiresPermissions("customerCard:add")
    @ResponseBody
    @RequestMapping("/add")
    public MsgModel add(@RequestBody CustomerCardModel model) {
        try {
            if(model.getCustomerId() == null){
                return new MsgModel("用户参数为空", ResultCode.FAILURE);
            }
            if(model.getCardId() == null){
                return new MsgModel("请选择会员卡类型", ResultCode.FAILURE);
            }
            if(model.getCreateId() == null){
                return new MsgModel("操作人不能为空", ResultCode.FAILURE);
            }
            //判断用户是否存在
            CustomerModel customer = customerFeign.getCustomer(model.getCustomerId());
            if (customer == null) {
                return new MsgModel("用户不存在", ResultCode.FAILURE);
            }
            User user = userFeign.getUserById(model.getCreateId());
            if(user == null){
                return new MsgModel("操作人不存在", ResultCode.FAILURE);
            }
            ShopModel shopModel = shopFeign.getShopByShopId(customer.getShopId());
            Integer roleId = userFeign.getRoleIdByUserId(model.getCreateId());
            boolean f = (roleId == 3 && user.getShopId() != customer.getShopId())
                    || (roleId == 5 && shopModel.getManagerId() != model.getCreateId());
            if(f){
                return new MsgModel(ErrorCodes.NO_PRIVILEGES.getMessage(), ResultCode.FAILURE);
            }
            //redis key
            String key = RedisConstantEnum.BUYCARD.getMessage() + customer.getCustomerPhone();

            //判断是否存在于redis中
            Boolean exists = redisFeign.exists(key);
            if (exists) {
                //获取redis中的key
                String sms = (String) redisFeign.get(key).getData();
                if (sms.equals(model.getVerificationCode())) {
                    model.setCustomerCode(customer.getCustomerCode());
                    model.setShopId(customer.getShopId());
                    model.setUser(user);
                    MsgModel msg = customerCardFeign.addCard(model);
                    redisFeign.delete(key);
                    return msg;
                } else {
                    return new MsgModel("验证码不正确", ResultCode.FAILURE);
                }
            } else {
                return new MsgModel("验证码不存在或者已过期", ResultCode.FAILURE);
            }
        } catch (Exception e) {
            logger.error("customerCardController add ====> {}", e);
            return new MsgModel("购买会员卡异常", ResultCode.FAILURE);
        }
    }

    @RequiresPermissions("customerCard:sms")
    @ResponseBody
    @RequestMapping("/sms")
    public MsgModel sms(@RequestBody CustomerCardModel customerCard) {
        try {
            CustomerModel customer = customerFeign.getCustomer(customerCard.getCustomerId());
            String phone = customer.getCustomerPhone();
            Boolean exists = redisFeign.exists(RedisConstantEnum.BUYCARD.getMessage() + phone);
            if (exists) {
                redisFeign.delete(RedisConstantEnum.BUYCARD.getMessage() + phone);
            }
            Gson gson = new Gson();
            String code = RandomNumUtil.getRandNum(number);
            SmsParamsModel smsParams = new SmsParamsModel();
            smsParams.setCode(code);
            String jsonParams = gson.toJson(smsParams);

            Boolean bo = smsSendFeign.sendSms(phone, jsonParams);
            if (bo) {
                redisFeign.set(RedisConstantEnum.BUYCARD.getMessage() + phone, code, 60000);
            }
            return new MsgModel(ResultCode.SUCCESS);
        } catch (Exception e) {
            logger.error("customerCardController sms ====> {}", e);
            return new MsgModel("验证异常", ResultCode.FAILURE);
        }
    }

    @ResponseBody
    @RequestMapping("/getListByCustomerId")
    public MsgModel getListByCustomerId(@RequestBody CustomerServiceTotalModel c) {
        try {
            List<CustomerServiceTotalModel> list = Optional.ofNullable(customerCardFeign.getListByCustomerId(c.getCustomerId())).orElse(Lists.newArrayList());
            if (list.isEmpty()) {
                return new MsgModel("无会员卡", ResultCode.FAILURE);
            }
            return new MsgModel(list.size(), list);
        } catch (Exception e) {
            logger.error("getListByCustomerCode ====> {}", e);
            return new MsgModel("获取会员卡异常", ResultCode.FAILURE);
        }
    }
}
